<template>
  <TableBoxMx :data="{
    disabled: data.disabled,
    tbody: data.tbody,
    columnKey: data.rowKey,
    isColumn: data.isColumn || ['specificationCode', 'goodsName', 'specificationName', 'goodsTypeName', 'totalStockQuantity', 'requestQuantity'],
    thead: [
      {
        label: '规格编号',
        prop: 'specificationCode',
        align: 'center',
        width: 120,
      },
      {
        label: '物料名称',
        prop: 'goodsName',
        align: 'left',
        width: 220,
      },
      {
        label: '规格型号',
        prop: 'specificationName',
        align: 'center',
        width: 160,
      },
      {
        label: '供应商',
        prop: 'supplierName',
        align: 'left',
        width: 160,
      },
      {
        label: '物料类型',
        prop: 'goodsTypeName',
        align: 'center',
        width: 80,
      },
      {
        label: '库存总数',
        prop: 'totalStockQuantity',
        align: 'center',
        width: 100,
      },
    ].concat(data.thead.map((el: any) => ({
      ...el,
      formProp: el.isRules ? data.prop : '',
    }))),
    //操作
    operation: data.operation,
  }">
    <template #[key]="{ row, index }" v-for="(slot, key) in $slots" :key="key">
      <slot :name="key" :row="row" :index="index" />
    </template>
    <template #totalStockQuantity="{ row }">
      <PopoverTabel :title="`${row.totalStockQuantity || 0}`" :width="700" :thead="[
        {
          label: '生产批次号',
          prop: 'productionBatchNumber',
          align: 'center',
          width: 120
        },
        {
          label: '生产日期',
          prop: 'productionDate',
          align: 'center',
          width: 100
        },
        {
          label: '库区',
          prop: 'warehouseAreaName',
          align: 'center',
          width: null
        },
        {
          label: '库位',
          prop: 'areaShelfName',
          align: 'center',
          width: null
        },
        {
          label: '库存数量',
          prop: 'stockQuantity',
          align: 'center',
          width: 100
        },
      ]" :tbody="row.details || []" />
    </template>
    <template #productionBatchNumber="{ row }" v-if="!data.disabled">
      <ElInputBox :data="row.productionBatchNumber">
        <template #append>
          <el-button @click.stop="() => {
            pup.state = true
            pup.row = row
            pup.form.list = row.details
          }">选择</el-button>
        </template>
      </ElInputBox>
    </template>
    <template #specificationCode="{ row }" v-if="!data.disabled">
      <div class="flex-center-center list-r-8" @click.stop="() => {
        pupMateriel.state = true
        pupMateriel.row = row
      }">
        <el-icon>
          <Switch />
        </el-icon>
        <span>{{ row.specificationCode }}</span>
      </div>
    </template>
  </TableBoxMx>
  <SelectCom :isCheckbox="true" :maring="0" :title="data.addSelect?.title" :selectable="(item: any) => {
    const _arr = data.tbody.map((el: any) => el[data.addSelect?.rowKey || data.rowKey])
    return !_arr.includes(item[data.addSelect?.rowKey || data.rowKey] || item.specificationCode)
  }" :search="{
    ...data.search,
    state: 1,//已确认 
    isShowDisabled: 0,//仅显示未作废的
  }" @selectBtn="selectBtn" @searchBtn="searchBtn" :table="data.addSelect" type="Materiel" v-if="!data.disabled">
    <template #search="{ search }" v-if="$slots.search">
      <slot name="search" :search="search" />
    </template>
    <el-button class="wAuto m-t-8" icon="Plus">添加明细</el-button>
  </SelectCom>
  <ElPupFormBox :pup="pupMateriel" isBg>
    <Materiel isRadio isSelect :goodRow="pupMateriel.row" :search="{
      state: 1,//已确认
      isShowDisabled: 0,//仅显示未作废的
    }" :thead="[
      {
        label: '物料编码',
        prop: 'goodsCode',
        align: 'center',
        width: 120,
        isCanSearch: true,
        hidden: true,
      },
      {
        label: '规格编号',
        prop: 'specificationCode',
        align: 'center',
        width: 120,
        isCanSearch: true,
      },
      {
        label: '物料名称',
        prop: 'goodsName',
        align: 'left',
        width: null,
        isCanSearch: true,
      },
      {
        label: '规格型号',
        prop: 'specificationName',
        align: 'center',
        width: 100,
        isCanSearch: true,
      },
      // {
      //   label: '转换比例',
      //   prop: 'specificationJsValue',
      //   align: 'center',
      //   width: 80
      // },
      {
        label: '物料类型',
        prop: 'goodsTypeName',
        align: 'center',
        width: 80
      },
      {
        label: '供应商',
        prop: 'supplierName',
        align: 'left',
        width: null,
      },
      {
        label: '单位',
        prop: 'goodsUnit',
        align: 'center',
        width: 80
      },
      {
        label: '库存数量',
        prop: 'totalStockQuantity',
        align: 'center',
        width: 80
      },
      {
        label: '批次明细',
        prop: 'details',
        align: 'center',
        width: 80
      },
    ]" @tableRadioBtn="(row: any) => {
      pupMateriel.row[data.rowKey] = row.specificationCode
      getSpecificationCodes()
      pupMateriel.state = false
    }"></Materiel>
  </ElPupFormBox>
  <ElPupFormBox :pup="pup" isBg>
    <template #default="{ form }">
      <CellBox title="新增批次" isTop v-if="data.productionBatchAdd">
        <div class="flex-start-center list-r-12">
          <div class="flex-start-center">
            <span>生产日期：</span>
            <ElDayBox :data="form" dataName="productionDate" :width="200" @changeBtn="(value: string) => {
              form.productionBatchNumber = value ? `${proxy.$day(value, 'YYMMDD')}` : ''
            }" />
          </div>
          <div class="flex-start-center">
            <span>批次编号：</span>
            <ElInputBox :data="form" dataName="productionBatchNumber" :width="200" />
          </div>
          <el-button type="primary" :disabled="!!!form.productionDate || !!!form.productionBatchNumber"
            @click="seveBtn(pup)">新建批次</el-button>
        </div>
      </CellBox>
      <CellBox title="库存批次" isTop>
        <TableBoxMx :data="{
          tbody: form.list,
          thead: [
            {
              label: '生产批次号',
              prop: 'productionBatchNumber',
              align: 'center',
              width: null
            },
            {
              label: '生产日期',
              prop: 'productionDate',
              align: 'center',
              width: null
            },
            {
              label: '库区',
              prop: 'warehouseAreaName',
              align: 'center',
              width: null
            },
            {
              label: '库位',
              prop: 'areaShelfName',
              align: 'center',
              width: null
            },
            {
              label: '库存数量',
              prop: 'stockQuantity',
              align: 'center',
              width: null
            },
          ],
          select: (row: any) => {
            setProductionBatch(pup, row)
          },
          selectable: (row: any) => {
            const _arr = data.tbody.map((el: any) => el.stockGoodsCode)
            return !_arr.includes(row.stockGoodsCode)
          },
        }">
          <template #productionDate="{ row }">
            {{ proxy.$day(row.productionDate) }}
          </template>
        </TableBoxMx>
      </CellBox>
    </template>
  </ElPupFormBox>
</template>
<script setup lang="ts">
import Materiel from '@/views/warehousewarehouseStting/materiel/index.vue'; // 生产物料
const { proxy } = getCurrentInstance() as any;
const props = withDefaults(
  defineProps<{
    data: any;
    height?: number;
  }>(),
  {
    data: {
      rowKey: 'specificationCode',
      prop: 'list',
      tbody: [],
      thead: [],
      operation: [],
    },
    minWidth: 280,
  },
);
const pupMateriel: any = reactive({
  state: false,
  typeName: 0,
  title: `替换物料`,
  row: {},
});
const pup = reactive({
  state: false,
  typeName: 0,
  title: `批次信息`,
  row: {},
  form: {
    productionDate: '',
    productionBatchNumber: '',
    list: []
  },
});
const seveBtn = (pup: any) => {
  //新建批次
  proxy.$api.InStockBill.AddProductionBatch({
    productionBatchNumber: pup.form.productionBatchNumber,
    productionDate: pup.form.productionDate,
  })
    .then((res: any) => {
      setProductionBatch(pup, res)
    }).catch(() => {
      pup.loading = false
    })
}
const setProductionBatch = (pup: any, row: any) => {
  pup.row.productionBatchCode = row.productionBatchCode//生产批次编码
  pup.row.productionBatchNumber = row.productionBatchNumber//生产批次号
  pup.row.productionDate = proxy.$day(row.productionDate)//生产日期
  pup.row.warehouseAreaCode = row.warehouseAreaCode//仓库分区代码
  pup.row.areaShelfCode = row.areaShelfCode//分区库位代码
  pup.row.stockGoodsCode = row.stockGoodsCode//库存code
  pup.row.stockQuantity = row.stockQuantity//库存数量
  pup.row.outStockQuantity = row.stockQuantity >= pup.row.requestQuantity ? pup.row.requestQuantity : row.stockQuantity//库存数量
  pup.state = false
}
//数组数据变化
watch(() => props.data?.tbody?.length, (newLength, oldLength) => {
  getSpecificationCodes()
}, { deep: true });

const getSpecificationCodes = () => {
  const _data = props.data
  if (_data.tbody?.length > 0) {
    const _specificationCodes = _data.tbody?.map((el: any) => el[_data.rowKey || _data.specificationCode])
    proxy.$api.Goods.GetPageGoodsSpecificationView({
      queryDataBaseFiled: 'specificationCode',
      likeWords: '',
      specificationCodes: _specificationCodes,
      pageIndex: 1,
      pageSize: _data.tbody.length,
      groupCode: '',
      supplierCode: '',
      state: -1,
      isShowDisabled: 0,
    }).then((res: any) => {
      _data.tbody.forEach((el: any, index: number) => {
        const _specificationCode = el[_data.rowKey]
        const _rowIndex = res.list.findIndex((find: any) => find.specificationCode === _specificationCode);
        if (_rowIndex !== -1) {
          const _row = res.list[_rowIndex]
          const _details = _row.details?.length > 0 ?
            JSON.parse(JSON.stringify(_row.details))
              .filter((el: any) => Number(el.stockQuantity) > 0)
            : []
          const _newRow = {
            ...el,
            specificationCode: _row.specificationCode,
            goodsName: _row.goodsName,
            specificationName: _row.specificationName,
            goodsTypeName: _row.goodsTypeName,
            totalStockQuantity: _row.totalStockQuantity,
            supplierName: _row.supplierName,
            goodsCode: _row.goodsCode,
            details: _details,
            stockQuantity: _row.details?.find((find: any) => find.stockGoodsCode === el.stockGoodsCode)?.stockQuantity || 0,
          }
          _data.tbody[index] = _newRow
        }
      })
    });
  }

};

const emit = defineEmits<{
  //fn为父组件引入子组件是定义的子组件事件属性，可随意定义
  (event: 'changeBtn', btn: any, value: any, row: any, rowArr?: any): void;
  (event: 'selectBtn', rowArr: any): void;
  (event: 'searchBtn'): void;
}>();
const selectBtn = (arr: any) => {
  emit('selectBtn', arr,);
};
const searchBtn = () => {
  emit('searchBtn');
};
onMounted(() => {
  getSpecificationCodes();
});
</script>
<style scoped lang="scss"></style>